package com.dlshouwen.core.base.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class UpDownLoadUtils {
	/**
	 * 上传文件方法
	 * @param request
	 * @param saveDir 保存目录
	 * @param realPrefPath 项目真实路径
	 * @return 逻辑保存目录+文件名
	 * @throws IOException 
	 */
	public static String uploadFile(MultipartFile multipartFile, String realPrefPath, String saveDir) throws IOException {
		String subDir = saveDir;
		if(null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
            String fileName = multipartFile.getOriginalFilename();
            int pos = fileName.lastIndexOf(".");
            fileName = fileName.substring(pos);
            String path = realPrefPath + saveDir;
            Date date = new Date();
            fileName = String.valueOf(date.getTime()) + fileName;
            subDir += "/" + fileName; 
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(path + "/" + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = null;
            InputStream s = null;
            try {
                fos = new FileOutputStream(file);
                s = multipartFile.getInputStream();
                byte[] buffer = new byte[1024];
                int read = 0;
                while ((read = s.read(buffer)) != -1) {
                    fos.write(buffer, 0, read);
                }
                fos.flush();
            } catch (Exception e) {
            	subDir = null;
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    fos.close();
                }
                if (s != null) {
                    s.close();
                }
            }
            if(null != subDir) {
            	subDir = subDir.replaceAll("\\\\", "/");
            }
        }
		return subDir;
	}
}
